package xyj.sparrow.scheduler.service.impl;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import xyj.sparrow.common.netty.bean.Result;
import xyj.sparrow.common.netty.bean.ResultCode;
import xyj.sparrow.scheduler.entity.Task;
import xyj.sparrow.scheduler.entity.TaskLog;
import xyj.sparrow.scheduler.mapper.TaskLogMapper;
import xyj.sparrow.scheduler.mapper.TaskMapper;
import xyj.sparrow.scheduler.service.ITaskLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jim
 * @since 2021-06-05
 */
@Service
public class TaskLogServiceImpl extends ServiceImpl<TaskLogMapper, TaskLog> implements ITaskLogService {
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();

    @Resource
    private TaskMapper taskMapper;

    @Override
    public void logStart(String logId, String appId, String taskId, String client,LocalDateTime now) {
        executorService.execute(() -> {
            Task task = taskMapper.selectById(taskId);
            TaskLog taskLog = new TaskLog();
            taskLog.setTaskLogId(logId);
            taskLog.setTaskId(taskId);
            taskLog.setTaskName(task == null ? "" : task.getTaskName());
            taskLog.setClientIp(client);
            taskLog.setStartTime(now);
            taskLog.setLogStatus(0);
            save(taskLog);
        });
    }

    @Override
    public void logError(String logId, String appId, String taskId, String msg,LocalDateTime now) {
        executorService.execute(() -> {
            Task task = taskMapper.selectById(taskId);
            TaskLog taskLog = new TaskLog();
            taskLog.setTaskLogId(logId);
            taskLog.setTaskId(taskId);
            taskLog.setTaskName(task == null ? "" : task.getTaskName());
            taskLog.setClientIp("");
            taskLog.setStartTime(now);
            taskLog.setEndTime(now);
            taskLog.setLogStatus(-1);
            taskLog.setLogMsg(msg);
            save(taskLog);
        });
    }

    @Override
    public void logEnd(Result<String> result) {
        executorService.execute(() -> {
            TaskLog taskLog = new TaskLog();
            taskLog.setTaskLogId(result.getData());
            taskLog.setEndTime(LocalDateTime.now());
            taskLog.setLogStatus(result.getCode().equals(ResultCode.SUCCESS.getCode()) ? 1 : -1);
            taskLog.setLogMsg(result.getMsg());
            updateById(taskLog);
        });
    }
}
